<?php
/**
 * Description: 获取上岸计划具体任务详情
 * User: devforma
 * Date: 15/1/7
 * Time: 11:53
 */

require __DIR__ . '/includes/utils.php';

class GetTaskDetail implements iController {
    private $userId, $questionShouldTransform = false;

    /**
     * api请求处理主函数
     * 
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        if (empty($queryArgs['task_id']) || !filter_var($queryArgs['task_id'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        //获取任务记录
        $task = DailyPlanUtils::getMissionRecord($queryArgs['task_id'], validateUser($queryArgs) !== 1);
        if (empty($task))
            return genOutput(1000);

        //用户id
        $this->userId = $queryArgs['user_id'];

        //题目格式改动
        if (!empty($queryArgs['app_version']) && version_cmp($queryArgs['app_version'], '1.1') >= 0)
            $this->questionShouldTransform = true;

        //根据任务类型分别处理
        switch ($task->mission_type) {
            case DailyPlanUtils::MISSIONTYPE_NOTELEARNING:  //知识点学习任务
            case DailyPlanUtils::MISSIONTYPE_NOTEREVIEW:    //知识点复习任务
                $result = $this->noteTaskDetail($task);
                break;

            case DailyPlanUtils::MISSIONTYPE_CURRENTAFFAIR: //时政热点任务
                $result = $this->shizhengTaskDetail($task);
                break;

            case DailyPlanUtils::MISSIONTYPE_NEWS:          //听新闻任务
                $result = $this->audioTaskDetail($task);
                break;

            case DailyPlanUtils::MISSIONTYPE_TEST:          //小测验任务
                $result = $this->ceyanTaskDetail($task, false);
                break;

            case DailyPlanUtils::MISSIONTYPE_WEEKTEST:      //周测验任务
                $result = $this->ceyanTaskDetail($task, true);
                break;

            default:
                return genOutput(1001);
        }

        return !empty($result) ? genOutput(1, $result) : genOutput(1001);
    }


    /**
     * 获取知识点任务详情
     *
     * @param Object $task 任务记录
     * @return array
     */
    private function noteTaskDetail($task) {
        $missionMeta = DailyPlanUtils::getMissionMeta();
        //获取该知识点的介绍
        $noteHierarchy = getNewNoteHierarchy();
        $description = $noteHierarchy[$task->mission_content_id]['note_desc'];

        $sortedGuileArray = $this->getNoteGuilei($task->mission_content_id);

        if (!empty($task->mission_content) && ($content = json_decode($task->mission_content))) {
            return array(
                'type' => $missionMeta[$task->mission_type]->type_name,
                'done' => $task->action_type == 1,
                'date' => date('Y-m-d', strtotime($task->action_time)),
                'note_id' => intval($task->mission_content_id),
                'name' => $task->mission_title,
                'accuracy' => floatval(number_format($content->accuracy, 3)),
                'average_accuracy' => floatval(number_format($content->average_accuracy, 3)),
                'rate' => floatval(number_format($content->rate, 3)),
                'description' => empty($description) ? '' : $description,
                'guilei' => $sortedGuileArray
            );
        }

        return array();
    }

    /**
     * 获取知识点下的归类信息
     *
     * @param int $noteId 知识点id
     * @return array
     */
    private function getNoteGuilei($noteId) {
        global $cmsdb;

        //根据知识点获取归类
        $sql = 'SELECT DISTINCT(p.post_mime_type) FROM `wp_posts` AS p INNER JOIN `relation_topic_note` AS n ON p.ID=n.topic_id AND n.note_id=:note_id WHERE p.post_mime_type!=""';
        $guileiArray = $cmsdb->getCol($sql, [':note_id' => $noteId]);

        //归类排序
        $sortedGuileArray = [];
        if (in_array('考点', $guileiArray, true)) $sortedGuileArray[] = ['id' => 1, 'name' => '考点'];
        if (in_array('技巧', $guileiArray, true)) $sortedGuileArray[] = ['id' => 2, 'name' => '技巧'];
        if (in_array('拓展', $guileiArray, true)) $sortedGuileArray[] = ['id' => 3, 'name' => '拓展'];

        return $sortedGuileArray;
    }

    /**
     * 获取时政详情
     * 
     * @param Object $task 任务记录
     * @return array
     */
    private function shizhengTaskDetail($task) {
        global $cmsdb;
        
        //获取时政信息
        $sql = "SELECT * FROM `{$cmsdb->politics}` WHERE id={$task->mission_content_id}";
        $shizheng = $cmsdb->getRow($sql);
        if (empty($shizheng)) return array();

        //获取时政评论
        $comments = array();
        $sql = "SELECT * FROM `{$cmsdb->politicsComment}` WHERE `politic_id`={$task->mission_content_id}";
        $childs = $cmsdb->getResults($sql);
        
        if (!empty($childs)) {
            foreach ($childs as $child) {
                if (trim($child->comment_name) == '评论标题') { //获取评论标题
                    $comments['name'] = trim($child->comment_value);
                } elseif (trim($child->comment_name == '评论作者')) { //获取评论作者
                    $comments['author'] = trim($child->comment_value);
                } else { //评论内容
                    if (!isset($comments['sections']))
                        $comments['sections'] = array();

		            /* 2015-10-8 ios老版本显示问题临时处理 */
                    if (!empty($_GET['terminal_type']) && $_GET['terminal_type'] == 'iOS_phone') {
                        $comments['sections'][] = array(
                            'title' => trim($child->comment_name),
                            'content' => trim($child->comment_value) . "\n"
                        );
                    } else{
                        $comments['sections'][] = array(
                            'title' => trim($child->comment_name),
                            'content' => trim($child->comment_value)
                        );
                    }
               }
            }
        }

        //内容替换处理
        $patterns = array('&amp;ldquo;', '&amp;rdquo;', '&amp;', '&nbsp;', "\n");
        $replaces = array('“', '”', '&', ' ', '<br />');
        
        return array(
            'type' => '时政热点',
            'timer_seconds' => intval(getOption('news_time_seconds')),
            'shizheng_id' => intval($shizheng->id),
            'done' => $task->action_type == 1,
            'date' => date('Y-m-d', strtotime($task->action_time)),
            'title' => trim(htmlspecialchars_decode($shizheng->politic_name)),
            'content' => trim(str_replace($patterns, $replaces, html_entity_decode($shizheng->politic_content))),
            'src_date' => $shizheng->politic_date,
            'comments' => $comments
        );
    }

    /**
     * 获取听新闻任务数据
     * 
     * @param Object $task 任务记录
     * @return array
     */
    private function audioTaskDetail($task) {
        global $cmsdb;
        
        //获取新闻信息
        $sql = "SELECT * FROM `$cmsdb->audioNews` WHERE `id`={$task->mission_content_id}";
        $news = $cmsdb->getRow($sql);
        
        return array(
            'done' => $task->action_type == 1,
            'type' => '新闻',
            'timer_seconds' => intval(getOption('news_time_seconds')),
            'date' => date('Y-m-d', strtotime($task->action_time)),
            'title' => $news->title,
            'content' => $news->content,
            'publish_time' => $news->publish_time,
            'audio_url' => $news->audio64_url
        );
    }

    /**
     * 获取测验任务详情(注册用户)
     * 
     * @param Object $task 任务记录
     * @param bool $isWeekTest 是否为周测验
     * @return array
     */
    private function ceyanTaskDetail($task, $isWeekTest = false) {
        //抽题数量
        $qCount = $isWeekTest ? 30 : 15;

        $answers = [];
        $accuracy = 0.0;
        $duration  = 0;

        //测验已完成
        if ($task->action_type != 0) {
            //答题内容
            $data = json_decode($task->mission_content);

            $answers = $data->answers;
            $accuracy = empty($data->accuracy) ? 0.0 : floatval(number_format($data->accuracy, 3));
            $duration = empty($data->duration) ? 0 : intval($data->duration);

            $ids = [];
            foreach ($data->answers as $answer) {
                $ids[] = $answer->id;
            }

            $questions = $this->questionShouldTransform ? getQuestionsByIds($ids) : getQuestions($ids);

        } else {
            if (empty($task->mission_content)) { //还未抽题
                $qids = $this->generateTestQuestions($this->userId, $task->id, $qCount, $isWeekTest);
            } else { //抽过题但没完成
                $qids = json_decode($task->mission_content);
            }

            //获取题目
            $questions = $this->questionShouldTransform ? getQuestionsByIds($qids) : getQuestions($qids);
        }

        return [
            'done' => $task->action_type == 1,
            'total_time' => $isWeekTest ? '30:00' : '15:00',
            'count' => $qCount,
            'questions' => $questions,
            'answers' => $answers,
            'date' => date('Y-m-d', strtotime($task->action_time)),
            'accuracy' => $accuracy,
            'duration' => $duration
        ];
    }

    /**
     * 生成测验任务题目
     *
     * @param int $userId 用户id
     * @param int $missionId 测验任务id
     * @param int $qCount 抽题数量
     * @param bool $isWeekTest 是否为周测验
     * @return array
     */
    private function generateTestQuestions($userId, $missionId, $qCount, $isWeekTest) {
        global $uddb, $cmsdb;

        $qids = []; //抽取的题目id

        /**--------------------------------------------------------------
        | 根据做过的知识点任务获取知识点
        ---------------------------------------------------------------*/
        if (!$isWeekTest) { //小测验
            $sql = "SELECT `mission_content_id` FROM `{$uddb->recentMissionInfo}` WHERE `mission_type` IN (:type1, :type2) AND `user_id`=:user_id AND `action_type`=1 AND `available`=1";

        } else { //周测验
            $sql = "SELECT `mission_content_id` FROM `{$uddb->recentMissionInfo}` WHERE `mission_type` IN (:type1, :type2) AND `user_id`=:user_id AND `action_type`=1";
        }

        $notes = (array)$uddb->getCol($sql, array(
            ':type1' => DailyPlanUtils::MISSIONTYPE_NOTELEARNING,
            ':type2' => DailyPlanUtils::MISSIONTYPE_NOTEREVIEW,
            ':user_id' => $userId
        ));


        /**--------------------------------------------------------------
        | 根据知识点取题
        ---------------------------------------------------------------*/
        $notesStr = implode(',', $notes);
        $sql = "SELECT q.id FROM `relation_question_note` AS n INNER JOIN `original_ztk_questions` AS q
         ON n.question_id=q.id WHERE n.note_id IN ({$notesStr}) AND q.type=1 AND q.is_handpick=1";
        $qPool = $cmsdb->getCol($sql);

        //随机抽题
        if (count($qPool) >= $qCount) {
            $randKeys = array_rand($qPool, $qCount);
            foreach ($randKeys as $key) {
                $qids[] = $qPool[$key];
            }

            //更新小测验抽题数据
            $uddb->update($uddb->recentMissionInfo, array('mission_content' => json_encode($qids)), array('id' => $missionId));
        }

        return $qids;
    }
}
